package com.industrial.premu.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuCustomIndicator;
import com.industrial.premu.domain.PreMuIndexWeight;
import com.industrial.premu.dto.IndexWeightParamsDto;
import com.industrial.premu.vo.PreMuIndexWeightMainVo;
import com.industrial.system.api.domain.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.industrial.common.log.annotation.Log;
import com.industrial.common.log.enums.BusinessType;
import com.industrial.common.security.annotation.RequiresPermissions;
import com.industrial.premu.domain.PreMuIndexWeightMain;
import com.industrial.premu.service.IPreMuIndexWeightMainService;
import com.industrial.common.core.web.controller.BaseController;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.page.TableDataInfo;

/**
 * 指标管理主Controller
 *
 * @author SangGuangCan
 * @date 2024-01-23
 */
@RestController
@RequestMapping("/main")
public class PreMuIndexWeightMainController extends BaseController
{
    @Autowired
    private IPreMuIndexWeightMainService preMuIndexWeightMainService;

    /**
     * 查询指标管理主列表
     */
//    @RequiresPermissions("premu:main:list")
    @GetMapping("/list")
    public TableDataInfo list(PreMuIndexWeightMain preMuIndexWeightMain)
    {
        startPage();
        List<PreMuIndexWeightMain> list = preMuIndexWeightMainService.selectPreMuIndexWeightMainList(preMuIndexWeightMain);
        return getDataTable(list);
    }

    /**
     * 导出指标管理主列表
     */
//    @RequiresPermissions("premu:main:export")
    @Log(title = "指标管理主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PreMuIndexWeightMain preMuIndexWeightMain)
    {
        List<PreMuIndexWeightMain> list = preMuIndexWeightMainService.selectPreMuIndexWeightMainList(preMuIndexWeightMain);
        ExcelUtil<PreMuIndexWeightMain> util = new ExcelUtil<PreMuIndexWeightMain>(PreMuIndexWeightMain.class);
        util.exportExcel(response, list, "指标管理主数据");
    }

    /**
     * 获取指标管理主详细信息
     */
//    @RequiresPermissions("premu:main:query")
    @GetMapping(value = "/{baseId}")
    public AjaxResult getInfo(@PathVariable("baseId") String baseId)
    {
        return success(preMuIndexWeightMainService.selectPreMuIndexWeightMainByBaseId(baseId));
    }

    /**
     * 新增指标管理主
     */
//    @RequiresPermissions("premu:main:add")
    @Log(title = "指标管理主", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PreMuIndexWeightMain preMuIndexWeightMain)
    {
        return preMuIndexWeightMainService.insertPreMuIndexWeightMain(preMuIndexWeightMain);
    }

    /**
     * 修改指标管理主
     */
//    @RequiresPermissions("premu:main:edit")
    @Log(title = "指标管理主", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PreMuIndexWeightMain preMuIndexWeightMain)
    {
        return preMuIndexWeightMainService.updatePreMuIndexWeightMain(preMuIndexWeightMain);
    }

    /**
     * <p>
     *     查询指标管理数据回显
     * </p>
     * @param preMuIndexWeightMain
     * @return
     */
    @GetMapping("/queryIndexValue")
    public AjaxResult queryIndexValue(PreMuIndexWeightMain preMuIndexWeightMain){
        return preMuIndexWeightMainService.queryIndexValue(preMuIndexWeightMain);
    }

    /**
     * 删除指标管理主
     */
//    @RequiresPermissions("premu:main:remove")
    @Log(title = "指标管理主", businessType = BusinessType.DELETE)
    @DeleteMapping("/{baseIds}")
    public AjaxResult remove(@PathVariable String[] baseIds)
    {
        return toAjax(preMuIndexWeightMainService.deletePreMuIndexWeightMainByBaseIds(baseIds));
    }


    /**
     * 导出指标管理数据
     * @param preMuIndexWeightMain
     * @param
     */
    @RequiresPermissions("premu:main:exportIndexManange")
    @PostMapping("/exportIndexManange")
    public void exportIndexManange(@RequestBody PreMuIndexWeightMain preMuIndexWeightMain,HttpServletResponse resp) throws UnsupportedEncodingException {

        preMuIndexWeightMain.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        Workbook wb = preMuIndexWeightMainService.exportIndexManange(preMuIndexWeightMain);
        String fileName = "123.xlsx";
        resp.setHeader("content-type", "application/octet-stream");
        resp.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        if (StringUtils.isBlank(fileName)) {
            fileName = UUID.randomUUID().toString().replace("-", "") + ".xlsx";
        }
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        OutputStream os = null;
        try {
            File touch = FileUtil.touch("/Users/sangguangcan/Desktop/temp/1.xlsx");
            os = resp.getOutputStream();
            if (wb != null) {
                wb.write(os);
//                wb.write(new FileOutputStream(touch));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * <p>
     *     新增指标管理
     * </p>
      * @param preMuIndexWeight
     * @return
     */
    @PostMapping("/addIndexManager")
    public AjaxResult addIndexManager(@RequestBody PreMuIndexWeight preMuIndexWeight){

        //获取当前用户所在的区县
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        preMuIndexWeight.setCounty(sysUser.getDistrict());

        if(StringUtils.isBlank(preMuIndexWeight.getYear()) || StringUtils.isBlank(preMuIndexWeight.getCompanyType())){
            return AjaxResult.warn("请选择年份或者是企业类型！");
        }
        preMuIndexWeightMainService.addIndexManager(preMuIndexWeight);
        return AjaxResult.success();
    }

    @GetMapping("/customIndicatorWeightValue")
    public AjaxResult customIndicatorWeightValue(PreMuCustomIndicator preMuCustomIndicator) {
        String district = SecurityUtils.getLoginUser().getSysUser().getDistrict();

        if (com.industrial.common.core.utils.StringUtils.isNotNull(preMuCustomIndicator.getCompanyType()) && com.industrial.common.core.utils.StringUtils.isNotNull(preMuCustomIndicator.getYear())) {
            IndexWeightParamsDto indexWeightParams = new IndexWeightParamsDto();
            indexWeightParams.setCounty(district);
            indexWeightParams.setCompanyType(preMuCustomIndicator.getCompanyType());
            indexWeightParams.setYear(preMuCustomIndicator.getYear());
            indexWeightParams.setIndexName("自定义指标");
            indexWeightParams.setId(preMuCustomIndicator.getId());
            List <PreMuIndexWeightMainVo> list = preMuIndexWeightMainService.weightList(indexWeightParams);
            if(CollectionUtils.isNotEmpty(list)){
                return AjaxResult.success(list.get(0).getIndexValue());
            }else{
                return AjaxResult.success();
            }
        }
        return AjaxResult.success();
    }

    @GetMapping("/weightCount")
    public AjaxResult weightCount(PreMuCustomIndicator preMuCustomIndicator) {
        String district = SecurityUtils.getLoginUser().getSysUser().getDistrict();

        IndexWeightParamsDto indexWeightParams = new IndexWeightParamsDto();
        indexWeightParams.setCounty(district);
        indexWeightParams.setCompanyType(preMuCustomIndicator.getCompanyType());
        indexWeightParams.setYear(preMuCustomIndicator.getYear());
        int count = preMuIndexWeightMainService.weightCount(indexWeightParams);
        if(count > 0){
            return AjaxResult.success(true);
        }else{
            return AjaxResult.success(false);
        }
    }
}
